<template>
	<view>
		<u-upload :accept="accept" :fileList="img" @afterRead="afterRead" @delete="deletePic" name="1" multiple
			:maxCount="maxCount">
		</u-upload>
	</view>
</template>

<script>
	import {
		baseApiUrl
	} from "@/util/publicConfig";
	import {
		getQueryHeaders
	} from "@/util/means/request";

	export default {
		props: {
			imgList: {
				type: Array,
				default: () => []
			},
			maxCount: {
				type: Number,
				default: 3
			},
			accept: {
				type: String,
				default: 'image'
			}
		},
		data() {
			return {
				img: []
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this.img.splice(event.index, 1)
				this.submit()
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.img.length
				lists.map((item) => {
					this.img.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.img[fileListLen]
					this.img.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.submit()
			},
			uploadFilePromise(url) {
				console.log(url, "url=================");
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${baseApiUrl}/common/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: getQueryHeaders(),
						success: (res) => {
							console.log(res, "uploadFilePromise##########################");
							setTimeout(() => {
								resolve(JSON.parse(res.data).message)
							}, 1000)
						}
					});
				})
			},
			submit() {
				this.$emit('submit', this.img)
			}
		},
		created() {
			this.img = this.imgList
		}
	}
</script>

<style>

</style>